package com.xone.xapp;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xone.xapp.HttpUtils.OnPostSuccessListener;

public class ProductItemUserActivity extends BasicActivity {
	protected final String TAG = ProductItemUserActivity.class.getSimpleName();
    protected LayoutInflater mInflater;
    protected String id;
    protected LinearLayout rootView;
	@Override
	public String getHeaderTitle() {
		return "用户产品详情";
	}
	@Override
	public int getContentView() {
		return R.layout.product_item_user;
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		Bundle bundle = this.getIntent().getExtras();
		id = (null == bundle) ? "" : bundle.getString("id");
		super.onCreate(savedInstanceState);
		if (!ContextUtils.isOnline(this)) {
			return;
		}
		if (null == id) {
			Toast.makeText(this, "缺少请求参数", Toast.LENGTH_SHORT).show();
			this.finish();
			return;
		}
		rootView = (LinearLayout)findViewById(R.id.product_item_details_zone);
		this.mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	protected void onResume() {
		super.onResume();
		List<View> tView = new ArrayList<View>();
		for (int i = 0; i < rootView.getChildCount(); i++) {
			View tv = rootView.getChildAt(i);
			String tag = (String)tv.getTag();
			if ("ImageArea".equals(tag) || "CheckList".equals(tag)) {
				tView.add(tv);
			}
		}
		for (View v : tView) {
			rootView.removeView(v);
		}
		showProgress();
		new InitDataTask(this, rootView, ContextUtils.getScreenWidth(this)).execute(id);
	}
	
	public class InitDataTask extends AsyncTask<String, Integer, JSONObject> {
		protected Context context;
		protected LinearLayout view;
		protected int imageWidth;
		protected ImageLoader imageLoader = null;
		public InitDataTask(Context context, LinearLayout view, int imageWidth) {
			this.context = context;
			this.imageWidth = imageWidth;
			this.view = view;
			imageLoader = new ImageLoader(context, imageWidth * 2);
		}
		@Override
		protected JSONObject doInBackground(final String... params) {
			if (isCancelled()) {
				return null;
			}
			List<NameValuePair> reqparams = new ArrayList<NameValuePair>();
			reqparams.add(new BasicNameValuePair("product.id", params[0]));
			return HttpUtils.httpGet(Constants.APP_URL + "/product/itemJsonDetailsForUser.html", reqparams, 
					new HttpUtils.onGetSuccessListener<JSONObject>() {
						@Override
						public JSONObject onSuccess(int status, String result) {
							if (HttpUtils.SC_OK == status) {
								JSONObject jsonObject = JSONUtils.getJSONObjectFromString(result);
								JSONObject product = JSONUtils.getJSONObjectForKey(jsonObject, "product");
								return product;
							} else {
								Toast.makeText(context, "Status Code:" + status, Toast.LENGTH_SHORT).show();
							}
							return null;
						}
					}, context);
		}
		@Override
		protected void onPostExecute(JSONObject result) {
			super.onPostExecute(result);
			if (null == result) {
				return;
			}
			JSONObject product = result;
			if (UserInfo.login) {
				boolean closeStatus = JSONUtils.getBooleanFromJSONObject(product, "closeStatus");
				if (!closeStatus) {
					//设置数据体
					ViewTag tag = new ViewTag();
					tag.setId(JSONUtils.getStringFromJSONObject(product, "id"));
					tag.setSaleType(JSONUtils.getStringFromJSONObject(product, "saleType"));
					view.findViewById(R.id.product_opt_info_border).setVisibility(View.VISIBLE);
					view.findViewById(R.id.product_opt_info_line).setVisibility(View.VISIBLE);
					//更新按钮的操作
					Button updateBtn = (Button)view.findViewById(R.id.apply_update);
					String checkStatus = JSONUtils.getStringFromJSONObject(product, "checkStatus");
					if (!"1".equals(checkStatus)) {
						updateBtn.setVisibility(View.VISIBLE);
					} else {
						updateBtn.setVisibility(View.GONE);
					}
					updateBtn.setTag(tag);
					updateBtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							updateButtonAction((ViewTag)v.getTag());
						}
					});
					//顶置按钮的操作
					Button topBtn = (Button)view.findViewById(R.id.apply_top);
					topBtn.setVisibility(View.VISIBLE);
					topBtn.setTag(tag);
					topBtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(final View v) {
							ContextUtils.confirm(getContext(), "确认申请顶置?", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									topButtonAction(view, v, (ViewTag)v.getTag());
								}
							});
						}
					});
					boolean closeable = JSONUtils.getBooleanFromJSONObject(product, "closeable");
					if (closeable) {
						Button closeBtn = (Button)view.findViewById(R.id.apply_close);
						closeBtn.setVisibility(View.VISIBLE);
						closeBtn.setTag(tag);
						closeBtn.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(final View v) {
								ContextUtils.confirm(getContext(), "确认关闭发布记录?", new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog, int which) {
										closeButtonAction(view, v, (ViewTag)v.getTag());
									}
								});
							}
						});
					}
				}
			}
			JSONArray checkList = JSONUtils.getJSONArrayForKey(product, "productCheckList");
			if (null != checkList && checkList.length() > 0) {
				view.findViewById(R.id.product_history_info_border).setVisibility(View.VISIBLE);
				view.findViewById(R.id.product_history_info_line).setVisibility(View.VISIBLE);
				for (int i = 0; i < checkList.length(); i++) {
					View mView = mInflater.inflate(R.layout.product_check_list_user, null);
					TextView dateCheckView = (TextView)mView.findViewById(R.id.dateCheck);
					TextView checkStatusNameView = (TextView)mView.findViewById(R.id.checkStatusName);
					TextView remarkView = (TextView)mView.findViewById(R.id.remark);
					JSONObject to = JSONUtils.getJSONObjectFromJSONArray(checkList, i);
					dateCheckView.setText(StringUtils.formatStringDate(JSONUtils.getStringFromJSONObject(to, "dateCheck")));
					checkStatusNameView.setText(JSONUtils.getStringFromJSONObject(to, "checkStatusName"));
					remarkView.setText(JSONUtils.getStringFromJSONObject(to, "remark"));
					mView.setTag("CheckList");
					view.addView(mView, 21 + i);
				}
			}
			int childCount = view.getChildCount();
			for (int i = 0 ; i < childCount; i++) {
				View v = view.getChildAt(i);
				String tag = (String)v.getTag();
				if (v instanceof LinearLayout && ("product".equals(tag) || "person".equals(tag))) {
					String key = context.getResources().getResourceEntryName(v.getId());
					if (null == key) {
						continue;
					}
					String value = null;
					if ("product".equals(tag)) {
						key = key.replaceFirst("product_", "");
						if (!product.isNull(key)) {
							value = JSONUtils.getStringFromJSONObject(product, key);
						}
					} 
					if (null != value) {
						TextView tv = (TextView)view.findViewById(context.getResources().getIdentifier(key, "id", context.getPackageName()));
						if (null != tv) {
							tv.setText(value);
						}
					}
				}
			}
			TextView dateCheckView = (TextView)view.findViewById(R.id.dateCheck);
			dateCheckView.setText(StringUtils.formatStringDate(dateCheckView.getText().toString()));
			JSONArray ids = JSONUtils.getJSONArrayForKey(product, "ids");
			if (null != ids && ids.length() > 0) {
				view.findViewById(R.id.product_image_info_border).setVisibility(View.VISIBLE);
				view.findViewById(R.id.product_image_info_line).setVisibility(View.VISIBLE);
				childCount = view.getChildCount();
				for (int i = 0; i < ids.length(); i++) {
					View mImageView = mInflater.inflate(R.layout.product_show_image, null);
					ImageView imageView = (ImageView)mImageView.findViewById(R.id.product_image_0);
					imageLoader.displayImage(Constants.APP_URL + "/assistant/image.html?id=" + JSONUtils.getStringFromJSONArray(ids, i), imageView);
					imageView.getLayoutParams().height = imageWidth;
					mImageView.setTag("ImageArea");
					view.addView(mImageView, childCount + i);
				}
			}
			view.setVisibility(View.VISIBLE);
			hideProgress();
		}
	}
	
	/**
	 * 点击更新按钮的事件
	 * @param tag
	 */
	protected void updateButtonAction(final ViewTag tag) {
		Intent i = new Intent(ProductItemUserActivity.this, ProductUpdateActivity.class);
		i.putExtra("id", tag.getId());
		i.putExtra("saleType", tag.getSaleType());
		startActivity(i);
	}
	/**
	 * 点击顶置按钮的事件
	 * @param tag
	 */
	protected void topButtonAction(final View view, final View btn, final ViewTag tag) {
		btn.setEnabled(false);
		showProgress();
		new AsyncTask<String, Void, JSONObject>() {
			@Override
			protected JSONObject doInBackground(String... params) {
				if (isCancelled()) {
					return null;
				}
				List<NameValuePair> param = new ArrayList<NameValuePair>();
				param.add(new BasicNameValuePair("overhead.refId", params[0]));
				param.add(new BasicNameValuePair("overhead.overheadType", params[1]));
				return HttpUtils.httpPost(Constants.APP_URL + "/product/doTopApplyJson.html", param, new OnPostSuccessListener<JSONObject>() {
					@Override
					public JSONObject onSuccess(int status, String result) {
						return JSONUtils.getJSONObjectFromString(result);
					}
				}, getContext());
			}
			protected void onPostExecute(JSONObject result) {
				hideProgress();
				super.onPostExecute(result);
				if (null == result) {
					Toast.makeText(getContext(), "操作失败", Toast.LENGTH_SHORT).show();
					btn.setEnabled(true);
					return;
				}
				JSONObject mapValue = JSONUtils.getJSONObjectForKey(result, "overhead");
				String message = "成功申请顶置";
				if (mapValue.isNull("id")) {
					message = "操作失败";
					btn.setEnabled(true);
				}
				Toast.makeText(getContext(), message, Toast.LENGTH_SHORT).show();
			}
		}.execute(tag.getId(), tag.getSaleType());
	}
	/**
	 * 点击关闭按钮的事件
	 * @param tag
	 */
	protected void closeButtonAction(final View view, final View btn, final ViewTag tag) {
		btn.setEnabled(false);
		showProgress();
		new AsyncTask<String, Void, JSONObject>() {
			@Override
			protected JSONObject doInBackground(String... params) {
				if (isCancelled()) {
					return null;
				}
				List<NameValuePair> param = new ArrayList<NameValuePair>();
				param.add(new BasicNameValuePair("product.id", params[0]));
				return HttpUtils.httpPost(Constants.APP_URL + "/product/doCloseRecordJson.html", param, new OnPostSuccessListener<JSONObject>() {
					@Override
					public JSONObject onSuccess(int status, String result) {
						return JSONUtils.getJSONObjectFromString(result);
					}
				}, getContext());
			}
			protected void onPostExecute(JSONObject result) {
				hideProgress();
				super.onPostExecute(result);
				if (null == result) {
					Toast.makeText(getContext(), "操作失败", Toast.LENGTH_SHORT).show();
					btn.setEnabled(true);
					return;
				}
				JSONObject mapValue = JSONUtils.getJSONObjectForKey(result, "mapValue");
				Toast.makeText(getContext(), JSONUtils.getStringFromJSONObject(mapValue, "msg"), Toast.LENGTH_SHORT).show();
			}
		}.execute(tag.getId());
	}
	
	protected class ViewTag {
		protected String id;
		protected String saleType;
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getSaleType() {
			return saleType;
		}
		public void setSaleType(String saleType) {
			this.saleType = saleType;
		}
	}
}
